/**
 * 数据库搜索数据操作模块
 */

const mongoose = require("mongoose");
const { Law, LawItem } = require("../schema/lawSchema");
const { SearchLaw, SearchLawItem } = require("../schema/searchSchema");
const {
  multiplePhraseSplit,
  splicing,
  createFullTextIndex,
} = require("../server/utilities/searchUtil");
const {
  lawExclusions,
  lawItemExclusions,
  lawNoIdx,
  lawItemNoIdx,
} = require("./common/common");
const { printBoxedLog } = require("./common/helpers");

/**
 * 创建并储存搜索文本
 */
async function initSearchData() {
  try {
    const laws = await Law.find({}).lean();
    const lawItems = await LawItem.find({}).lean();
    const searchLawData = laws.map((law) => {
      const lawCopy = { ...law };
      const keys = Object.keys(lawCopy);
      for (let key of keys) {
        if (lawExclusions.includes(key)) {
          continue;
        } else if (key === "_id") {
          lawCopy.mapping = new mongoose.Types.ObjectId(lawCopy[key]);
          delete lawCopy[key];
        } else {
          lawCopy[key] = splicing(multiplePhraseSplit(lawCopy[key]));
        }
      }
      return lawCopy;
    });

    // 创建lawItem搜索数据时，要处理嵌套关系
    const searchLawItemData = lawItems.map((lawItem) => {
      const lawItemCopy = { ...lawItem };
      const keys = Object.keys(lawItemCopy);
      for (let key of keys) {
        if (lawItemExclusions.includes(key)) {
          continue;
        } else if (key === "_id") {
          lawItemCopy.mapping = new mongoose.Types.ObjectId(lawItemCopy[key]);
          delete lawItemCopy[key];
        } else if (Array.isArray(lawItemCopy[key])) {
          //当该属性是一个数组时
          lawItemCopy[key] = lawItemCopy[key].map((elem) => {
            if (typeof elem === "object" && elem.text) {
              elem.text = splicing(multiplePhraseSplit(elem.text));
            }
            return elem;
          });
        } else {
          lawItemCopy[key] = splicing(multiplePhraseSplit(lawItemCopy[key]));
        }
      }
      return lawItemCopy;
    });

    const messages = [];

    // 删除之前的数据
    await SearchLaw.deleteMany({}).then(messages.push("标题搜索数据删除成功"));
    await SearchLawItem.deleteMany({}).then(
      messages.push("全文搜索数据删除成功")
    );

    //删除索引
    await SearchLaw.collection.dropIndexes();
    await SearchLawItem.collection.dropIndexes();
    messages.push("索引删除成功");

    // 创建索引
    await createFullTextIndex(SearchLaw, lawNoIdx);
    messages.push("标题搜索索引创建成功");
    await createFullTextIndex(SearchLawItem, lawItemNoIdx);
    messages.push("全文搜索索引创建成功");

    // 插入数据
    await SearchLaw.insertMany(searchLawData).then(
      messages.push("标题搜索数据插入成功")
    );
    await SearchLawItem.insertMany(searchLawItemData).then(
      messages.push("全文搜索数据插入成功")
    );

    // 格式化打印日志数据
    printBoxedLog(messages);
  } catch (err) {
    console.error(err);
  }
}

module.exports = initSearchData;
